from flask import Blueprint, current_app, request, jsonify
from database import db, User
import jwt
import re
import os

user = Blueprint('user', __name__, url_prefix='/user')


@user.route('/new', methods=['POST'])
def new():
    print("=== 收到注册请求 ===")
    print("请求头:", dict(request.headers))
    print("请求方法:", request.method)
    print("请求内容类型:", request.content_type)

    # 调试请求体内容
    try:
        raw_data = request.get_data(as_text=True)
        print("原始请求体:", raw_data)
    except Exception as e:
        print("获取原始请求体失败:", e)
        return jsonify({'status': 'invalid request data', 'details': str(e)}), 400

    # 从表单数据获取用户名和密码
    username = request.form.get("username")
    password = request.form.get("password")
    print("从表单获取 - username:", username, "password:", password)

    # 参数为空检查
    if username is None or password is None:
        print("用户名或密码为空")
        return jsonify({'status': 'username and password are required'}), 400

    # 转换为字符串并去除空格
    username = str(username).strip() if username else ""
    password = str(password).strip() if password else ""
    print("处理后的 - username:", repr(username), "password:", repr(password))

    # 空字符串检查
    if not username or not password:
        print("用户名或密码为空字符串")
        return jsonify({'status': 'username and password cannot be empty'}), 400

    # 长度检查
    if len(username) > 16 or len(password) > 16:
        print("用户名或密码过长")
        return jsonify({'status': 'username/password too long'}), 400

    # 用户名格式检查
    if re.match("^[\w_-]+$", username) is None:
        print("用户名格式无效")
        return jsonify({'status': 'invalid username'}), 400

    # 检查用户名是否已存在
    try:
        existing_user = User.query.filter_by(username=username).first()
        if existing_user is not None:
            print("用户名已存在")
            return jsonify({'status': 'username already used'}), 400
    except Exception as e:
        print("数据库查询错误:", e)
        return jsonify({'status': 'db error 1'}), 500

    # 创建新用户
    try:
        new_user = User(username=username, password=password, random=os.urandom(8).hex())
        db.session.add(new_user)
        db.session.commit()
        print("用户创建成功")
        return jsonify({'status': 'success'}), 201
    except Exception as e:
        db.session.rollback()
        print("数据库提交错误:", e)
        return jsonify({'status': 'db error 2'}), 500


@user.route('/login', methods=['POST'])
def login():
    print("=== 收到登录请求 ===")
    print("请求头:", dict(request.headers))
    print("请求方法:", request.method)
    print("请求内容类型:", request.content_type)

    # 从表单数据获取用户名和密码
    username = request.form.get("username")
    password = request.form.get("password")
    print("从表单获取 - username:", username, "password:", password)

    # 参数验证
    if username is None or password is None:
        print("用户名或密码为空")
        return jsonify({'status': 'username and password are required'}), 400

    username = str(username).strip() if username else ""
    password = str(password).strip() if password else ""
    print("处理后的 - username:", repr(username), "password:", repr(password))

    if not username or not password:
        print("用户名或密码为空字符串")
        return jsonify({'status': 'username and password cannot be empty'}), 400

    # 查询用户
    try:
        user_obj = User.query.filter_by(username=username, password=password).first()
        if user_obj is None:
            print("登录失败：用户名或密码错误")
            return jsonify({'status': 'login failed'}), 401
    except Exception as e:
        print("数据库查询错误:", e)
        return jsonify({'status': 'db error'}), 500

    # 生成 JWT token
    try:
        token = jwt.encode(
            {'username': username},
            current_app.config['JWT_SECRET_KEY'],
            algorithm='HS256'
        )
        # 兼容不同版本的 PyJWT
        if isinstance(token, bytes):
            token = token.decode('utf-8')

        print("登录成功，生成 token")
        return jsonify({'status': 'success', 'token': token}), 200

    except Exception as e:
        print("Token 生成错误:", e)
        return jsonify({'status': 'token generation failed'}), 500


@user.after_request
def add_cors_headers(response):
    response.headers['Access-Control-Allow-Origin'] = '*'
    response.headers['Access-Control-Allow-Methods'] = 'POST, OPTIONS'
    response.headers['Access-Control-Allow-Headers'] = 'Content-Type'
    return response


@user.before_request
def handle_options():
    if request.method == 'OPTIONS':
        # 直接返回空响应，CORS 头由 after_request 添加
        return '', 204